<?php
/**
 * 
 * @authors Liujinbi (857053791@QQ.com)
 * @date    2017-07-29 17:00:05
 * @version $Id$
 */

namespace app\mall\controller;

use think\Db;
use think\Request;
use think\Config;
use think\Controller;

class Goods extends Controller {
    
    /**
     * 根据条件返回商品
     * @return [type] [description]
     */
    function index(){
    	$kw = Request()->param();

        //商品分类
        $temp_category = Db::name('goods_category')->where(['cate_status'=>1])->select();
        $category = [];
        foreach ($temp_category as $k => $v) {
            $category[$v['cate_id']] = $v;
        }

    	$query = Db::table('sdzx_goods')->alias('g')
    	->field('g.goods_id,g.goods_name,g.unit,g.category_id,g.category_id_1,g.category_id_2,g.category_id_3,g.keywords,g.introduction,g.sort,g.picture,max(sval.price) as max_price,min(sval.price) as min_price,max(sval.is_hot) as is_hot,min(sval.sellout) as goods_sellout,max(sval.is_recommend) as is_recommend,max(sval.is_new) as is_new,max(sval.is_cutprice) as is_cutprice,sum(sval.sales) as sales, max(sval.is_hot) as  is_promotion, b.brand_name')
    	->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id and sval.status=1')
        ->join('sdzx_goods_brand b','g.brand_id=b.brand_id','left')
    	->where("sval.status=1")
        ->order('g.category_id_3 asc')
    	->group('g.goods_id');

    	if (isset($kw['cate_id']) && !empty($kw['cate_id'])) {
            $cat = CAT('goods_category',array('cate_id','cate_pid','cate_name','fullname'),'cate_status=1');
            $cate_ids = implode(',',array_column($cat->getChildren($kw['cate_id'],$category),'cate_id'));
    		$query->where("g.category_id in ({$cate_ids})");
    	}
    	if (isset($kw['is_hot']) && !empty($kw['is_hot'])) { //后面来修改
    		$query->where("is_hot=1");
    	}
    	if (isset($kw['brand']) && !empty($kw['brand'])) {
    		$query->where("g.brand_id in ({$kw['brand']})");
    	}
    	if (isset($kw['name']) && !empty($kw['name'])) {
            $name = explode(',',$kw['name']);
            $orw = '';
            foreach ($name as $key => $value) {
                $orw .= " g.goods_name like '%{$value}%' or g.keywords like '%{$value}%' or b.brand_name like '%{$value}%' or ";
            }
    		$query->where(rtrim($orw,'or '));
    	}
 
    	if (isset($kw['sales']) && !empty($kw['sales'])) {
    		$query->order('sales desc');
    	}else{
    		$query->order('g.sort desc');
    	}
    	$page = isset($kw['page'])?$params['page']:1;
    	// $list = $query->page($page,Config::get('paginate.list_rows'))->fetchSql(false)->select();
        $list = $query->select();
        
        $tmp_g=false;$tmp_n=0;
        $return_arr=[];
        foreach ($list as $k => $v) {
            if ( $tmp_g !== false) {
                if ($tmp_g!=$v['category_id_3']) { //加一组
                    $tmp_g=$v['category_id_3'];
                    $return_arr[$k+$tmp_n]=['is_title'=>true,'title'=>$category[$tmp_g]['cate_name'],'cate_id'=>$tmp_g];
                    $tmp_n++;
                }
            }else{
                $tmp_g = $v['category_id_3'];
                if ($tmp_g!=0) { //加一组
                    
                    $return_arr[$k+$tmp_n]=['is_title'=>true,'title'=>$category[$tmp_g]['cate_name'],'cate_id'=>$tmp_g];
                    $tmp_n++;
                }
            }
            $tmp = Db::connect([],'sval')->field('sval.*,s.supplier_name')
            ->table('sdzx_goods_specval')->alias('sval')
            ->join('sdzx_supplier s','sval.supplier_id=s.supplier_id','left')
            ->where(['goods_id'=>$v['goods_id']])->select();
            $return_arr[$k+$tmp_n] = $list[$k];
            $return_arr[$k+$tmp_n]['is_title']=false;

            if (sizeof($tmp)>1) {
                $return_arr[$k+$tmp_n]['specval_price'] = null;
                if ($list[$k]['min_price']==$list[$k]['max_price']) {
                    $return_arr[$k+$tmp_n]['unit_price'] = $list[$k]['max_price'];
                }else{
                    $return_arr[$k+$tmp_n]['unit_price'] = $list[$k]['min_price'].'-'.$list[$k]['max_price'];
                }
            }else{
                $return_arr[$k+$tmp_n]['unit'] = $tmp[0]['unit'];
                $return_arr[$k+$tmp_n]['specval_price'] = $tmp[0]['price'];
                $return_arr[$k+$tmp_n]['unit_price'] = $tmp[0]['unit_price'];
            }
            $return_arr[$k+$tmp_n]['list']=$tmp;
        }
    	$this->success('success','',$return_arr);
    }

    /**
     * 商品搜索
     * @return [type] [description]
     */
    public function search()
    {
        $kw = Request()->param();
        $w = false;

        $query = Db::table('sdzx_goods')->alias('g')
        ->field('g.goods_id,g.goods_name,g.unit,g.category_id,g.category_id_1,g.category_id_2,g.category_id_3,g.keywords,g.introduction,g.sort,g.picture,max(sval.price) as max_price,min(sval.price) as min_price,max(sval.is_hot) as is_hot,min(sval.sellout) as goods_sellout,max(sval.is_recommend) as is_recommend,max(sval.is_new) as is_new,max(sval.is_cutprice) as is_cutprice,sum(sval.sales) as sales, max(sval.is_hot) as  is_promotion, b.brand_name')
        ->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id and sval.status=1')
        ->join('sdzx_goods_brand b','g.brand_id=b.brand_id','left')
        ->where("sval.status=1")
        ->order('g.category_id_3 asc')
        ->group('g.goods_id');

        if (isset($kw['cate_id']) && !empty($kw['cate_id'])) {
            //商品分类
            $temp_category = Db::name('goods_category')->where(['cate_status'=>1])->select();
            $category = [];
            foreach ($temp_category as $k => $v) {
                $category[$v['cate_id']] = $v;
            }

            $cat = CAT('goods_category',array('cate_id','cate_pid','cate_name','fullname'),'cate_status=1');
            $cate_ids = implode(',',array_column($cat->getChildren($kw['cate_id'],$category),'cate_id'));
            $query->where("g.category_id in ({$cate_ids})");
            $w = true;
        }
        if (isset($kw['is_hot']) && !empty($kw['is_hot'])) { //后面来修改
            $query->where("is_hot=1");
            $w = true;
        }
        if (isset($kw['brand']) && !empty($kw['brand'])) {
            $query->where("g.brand_id in ({$kw['brand']})");
            $w = true;
        }
        if (isset($kw['name']) && !empty($kw['name'])) {
            $name = explode(',',$kw['name']);
            foreach ($name as $key => $value) {
                $query->where("g.goods_name like '%{$value}%' or g.keywords like '%{$value}%' or b.brand_name  like '%{$value}%' or CONCAT(b.brand_name,g.goods_name) like '%{$value}%'");
            }
            $w = true;
        }
 
        if (isset($kw['sales']) && !empty($kw['sales'])) {
            $query->order('sales desc');
        }else{
            $query->order('g.sort desc');
        }
        $page = isset($kw['page'])?$params['page']:1;
        // $list = $query->page($page,Config::get('paginate.list_rows'))->fetchSql(false)->select();
        if ($w) {
            $list = $query->select();
        }else{
            $list = [];
        }
        

        //商品规格
        foreach ($list as $k => $v) {
            $tmp = Db::connect([],'sval')->name('goods_specval')->where(['goods_id'=>$v['goods_id'],'status'=>1])->order('price asc')->select();
            // $cur = array_shift($tmp);
            $unit = $v['unit'];
            $list[$k] = array_merge($list[$k],$tmp[0]);
            if (sizeof($tmp)>1) {
                $list[$k]['list']=$tmp;
                $list[$k]['unit']=$unit;
            }
        }

        // foreach ($list as $k => $v) {
        //     $tmp = Db::connect([],'sval')->field('sval.*,s.supplier_name')
        //     ->table('sdzx_goods_specval')->alias('sval')
        //     ->join('sdzx_supplier s','sval.supplier_id=s.supplier_id','left')
        //     ->where(['goods_id'=>$v['goods_id']])->select();
        //     if (sizeof($tmp)>1) {
        //         $list[$k]['specval_price'] = null;
        //         $list[$k]['unit_price'] = $list[$k]['min_price'].'-'.$list[$k]['max_price'];
        //     }else{
        //         $list[$k]['specval_price'] = $tmp[0]['price'];
        //         $list[$k]['unit_price'] = $tmp[0]['unit_price'];
        //     }
        //     $list[$k]['list']=$tmp;
        // }

        $this->success('success','',['list'=>$list]);
    }

    /**
     * 热门搜索
     * @return [type] [description]
     */
    public function hotSearch()
    {
        $query = Db::table('sdzx_goods')->alias('g')
        ->field('g.goods_name')
        ->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id and sval.status=1')
        ->where("sval.status=1")
        ->order('g.clicks desc,sval.is_hot desc')
        ->group('g.goods_id');

        $list = $query->limit(0,10)->select();
        $return_arr = array_column($list,'goods_name');
        $this->success('success','',$return_arr);
    }

    /**
     * 商品详情
     * @return [type] [description]
     */
    function detail(){
    	$data = Request()->only('goods_id,specval_id','get');
    	if (empty($data['goods_id'])) {
    		$this->error('参数错误','back');
    	}
    	$info = Db::name('goods')
    	->where(['goods_id'=>$data['goods_id']])
    	->find();
    	if (empty($info)) {
    		$this->error('该商品已下架','back');
    	}

        //商品评价
        $evaluate = Db::name('goods_evaluate')->where("find_in_set({$data['goods_id']},goods_id)")->find();
        $info['evaluate'] = $evaluate;


        //商品规格
    	$sval = Db::name('goods_specval')->where(['goods_id'=>$data['goods_id'],'status'=>1])->order('sort desc,specval_id asc')->select();
    	if (empty($sval)) {
    		$this->error('该商品已下架','back');
    	}
    	$cur = [];
    	foreach ($sval as $k => $v) {
			if (isset($data['specval_id']) && ($v['specval_id']==$data['specval_id'])) {
				$v['is_curr'] = 1;
				$cur=$v;
			}else{
				$v['is_curr'] = 0;
			}
			$sval[$k]=$v;
		}

    	if (empty($cur)) {
    		$sval[0]['is_curr']=1; $cur=$sval[0];
    	}
    	$info['list']=$sval;

    	$info['img_lists'] = explode(',', $info['img_lists']);
    	$return_arr = array_merge($info,$cur);
        if ($info['picture']) {
            array_unshift($info['img_lists'],$info['picture']);
        }

    	if (empty($info['img_lists'][0])) {
            $info['img_lists']=array();
        }
		$info['description'] = htmlspecialchars_decode($info['description']);
		$info['scheduling']  = Config::get('sites.scheduling');
    	$this->success('success','',$info);
    }

    /**
     * 首页推荐商品
     * @return [type] [description]
     */
    function recGoods(){
    	$data = Request()->param();

        $goods = Db::table('sdzx_goods')->alias('g')
        ->field('g.goods_id,g.brand_id,g.brand_name,g.goods_name,g.unit,g.category_id_1,cate.cate_name,g.keywords,g.introduction,g.sort,g.picture,max(sval.price) as max_price,min(sval.price) as min_price,max(sval.is_hot) as is_hot,min(sval.sellout) as goods_sellout,max(sval.is_recommend) as is_recommend,max(sval.is_new) as is_new,max(sval.is_cutprice) as is_cutprice,sum(sval.sales) as sales, max(sval.is_hot) as  is_promotion ')
        ->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id and sval.status=1')
        ->join('sdzx_goods_category cate','g.category_id_1=cate.cate_id')
        ->where("sval.status=1 and sval.is_recommend=1")
        ->group('g.goods_id')
        ->select();

        
        // 循环取出规格
        $tmp_list=[];
        foreach ($goods as $k => $v) {
            // $tmp_sval = Db::connect([],'sval')->table('sdzx_goods')->alias('g')
            // ->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id')
            // ->where("sval.goods_id={$v['goods_id']} and sval.status=1")->select();
            $tmp_sval = Db::connect([],'sval')->name('goods_specval')->where(['goods_id'=>$v['goods_id'],'status'=>1])->order('price asc')->select();
            // $cur = array_shift($tmp_sval);
            $unit = $v['unit'];
            $cur=$tmp_sval[0];
            unset($cur['is_cutprice'],$cur['is_hot'],$cur['is_recommend'],$cur['is_new']);
            $tmp_goods = array_merge($goods[$k],$cur);
            if (sizeof($tmp_sval)>1) {
                $tmp_goods['list']=$tmp_sval;
                $tmp_goods['unit']=$unit;
            }
            $tmp_list[]=$tmp_goods;
        }

        // 商品归类
        $list=[];
        foreach ($tmp_list as $key => $value) {
            $list[$value['category_id_1']]['title']=$value['cate_name'];
            $list[$value['category_id_1']]['id']=$value['category_id_1'];
            $list[$value['category_id_1']]['list'][]=$value;
        }

	    //分类广告
	    foreach ($list as $key => $value) {
	    	$advlist_tim = Db::connect([],'adv')->field('adp.adp_name,adv.adv_name,adv.adv_id,adv.adv_url,adv.adv_img')
	    	->table('sdzx_goods_category')->alias('cate')
	    	->join('sdzx_adposition adp','cate.adp_id=adp.adp_id')
	    	->join('sdzx_adv adv','adp.adp_id=adv.adp_id')
	    	->where("cate.cate_id={$key}")
	    	->find();
            if ($advlist_tim) {
                $list[$key]['advlist']=$advlist_tim;
            }
	    	
	    }

	    $return_list=[];
	    foreach ($list as $key => $value) {
	    	array_push($return_list, $value);
	    }
    	$this->success('success','',$return_list);
    }

    /**
     * 进入减价
     * @return [type] [description]
     */
    public function todayCutprice()
    {
        $goods = Db::table('sdzx_goods')->alias('g')
        ->field('g.goods_id,g.goods_name,g.brand_id,g.brand_name,g.unit,g.category_id,g.keywords,g.introduction,g.sort,g.label_id,g.picture,max(sval.price) as max_price,min(sval.price) as min_price,max(sval.is_hot) as is_hot,min(sval.sellout) as goods_sellout,max(sval.is_recommend) as is_recommend,max(sval.is_new) as is_new,max(sval.is_cutprice) as is_cutprice,sum(sval.sales) as sales, max(sval.is_hot) as  is_promotion ')
        ->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id and sval.status=1')
        ->where("sval.status=1 and sval.is_cutprice=1")
        ->group('g.goods_id')
        ->select();

        //商品规格
        foreach ($goods as $k => $v) {
            $tmp = Db::connect([],'sval')->name('goods_specval')->where(['goods_id'=>$v['goods_id'],'status'=>1])->order('price asc')->select();
            // $cur = array_shift($tmp);
            $unit = $v['unit'];
            $goods[$k] = array_merge($goods[$k],$tmp[0]);
            if (sizeof($tmp)>1) {
                $goods[$k]['list']=$tmp;
                $goods[$k]['unit']=$unit;
            }
        }

        $this->success('success','',['list'=>$goods]);
    }

    /**
     * 评价商品
     * @return [type] [description]
     */
    function evaluate(){
        $param = Request()->param();
        !$param['order_id'] && $this->error('参数错误');

        //查出商品
        $goods = Db::name('order_goods')->where(['order_id'=>$param['order_id']])->select();

        $evaluate = [
            'goods_id'      => implode(',', array_column($goods, 'goods_id')),
            'user_id'       => $this->uid,
            'user_name'     => $this->user['nickname']?:$this->user['realname']?:$this->user['username'],
            'order_id'      => $param['order_id'],
            'content'       => $param['content'],
            'score'         => $param['score'],
            'evaluate_time' => date('Y-m-d H:i:s')
        ];

        $re = Db::name('goods_evaluate')->insert($evaluate);
        if ($re) {
            Db::name('order')->where(['order_id'=>$param['order_id']])->update(['is_evaluate'=>1]);
            $this->success('评价成功');
        }else{
            $this->error('评价失败');
        }
    }

    /**
     * 商品评价列表
     * @return [type] [description]
     */
    function evaluateList(){
        $param = Request()->param();

        $Query = Db::name('goods_evaluate');
        if ($param['goods_id']) {
            $Query->where(['goods_id'=>$param['goods_id']]);
        }

        $page = $param['page']?:1;
        // $list = $Query->page($page,Config::get('paginate.list_rows'))->select();
        $list = $Query->select();
        $this->success('success','',$list);
    }
}